
<template>
	<div class="indexbody">
		<top></top>
		<div class="main">
			<banner></banner>
			<page-tip strEnd="farm" showClose>{{lang.pageTip[lp]}}</page-tip>
			<page-tip strEnd="manageAffiche1" showClose>
				<tip-manage></tip-manage>
			</page-tip>
			<float-tip strEnd="farm2" showClose>
				<p class="f14" style="color:#ff5500">JustSwap已改版，必须使用合约地址来搜索代币，无法使用代币名称搜索。</p>
			</float-tip>

			<!-- 公開信息 -->
			<div class="public_infomation" >
				<div class="wrap">
					<!--總鎖倉-->
					<div class="box box1">
						<div class="item">{{lang.data_all[lp]}}<a href="#/main/rule" target="_self">[{{lang.data_rule[lp]}}]</a></div>
						<div class="data">≈ <span class="">{{totalTrx*trxPrice|num}} USD</span></div>
					</div>

					<div class="box box1">
						<div class="item">
							{{xg.name + lang.data_price[lp]}}
							<a :href="'https://justswap.org/?lang=zh-CN#/home?tokenAddress='+xg.address+'&type=swap'" class="" target="_self">
								{{lang.pool_toSwap[lp]}}
							</a>

						</div>
						<div class="data">≈ <span class="">{{xg.toUsdtPrice|num}} USD</span></div>
					</div>

					<!--總流通-->
					<div class="box box2">
						<div class="item">
							{{lang.data_circulate[lp]}}
							<a :href="'https://justswap.org/?lang=zh-CN#/home?tokenAddress='+xg.address+'&type=add'" class="" target="_self">
								JustSwap{{lang.data_get[lp]}}LP Token
								<i class="f18 el-icon-question" @click.prevent="ReadMelpToken()"></i>
							</a>
						</div>
						<div class="data"><span class="">{{totalRelease|num}}</span></div>
					</div>
				</div>

				<div class="tip-row">
					<div>{{xg.name + lang.data_address[lp]}}
						<el-tooltip class="" effect="dark" :content="lang.data_tip1[lp]" placement="top-start"><i class="f18 el-icon-question"></i></el-tooltip>：
					</div>
					<span class="copytext ">{{xg.address}}</span>
					<span class="JS-copy pointer"><i class="c-333 f20 fa fa-copy ml5"></i></span>

				</div>
				<div class="tip-row">
					<span>{{projectTitle + lang.data_pool_open[lp]}} <a href="#/main/rule" target="_self">{{lang.data_pool_open_check[lp]}}</a></span>
				</div>

				<div class="tip-row">
					<span >推廣挖礦：介紹的玩家通過遊戲每獲得1個代幣，推廣人員獲得0.2個<a  href="#/uc/share" target="_self">前往推廣</a></span>
				</div>


			</div>

			<!--额外公告-->
			<div class="public_infomation">
				<div class="affiche">
					<div class="pub-info-title flex flex-jc-sb">
						<div class="c-blue b">项目进展</div>
						<div class="close">
							<i class="fa f18 fa-angle-double-up " v-if="afficheVisible==true" @click="afficheVisible=false"></i>
							<i class="fa f18 fa-angle-double-down" v-if="afficheVisible==false" @click="afficheVisible=true"></i>
						</div>
					</div>
					<div class="content" v-show="afficheVisible">
						<div class="af-row">世界盃競猜將於2022年上線。其它熱門賽事將根據賽事周期與社區熱度依次上線</div>
						<!--<div class="af-row">2021三月份开始部署上所事项，暂定抹茶、比特儿甚至争取三大所上架XG （交易所上币对社区人数有一定要求，家人们要共同努力一起拉新用户进入xGAME大家庭，争取尽快上所）</div>-->
						<div class="af-row">
							<el-popover placement="top" width="180">
								<img src="images/bananatok_group.png" width="100%" alt="">
								<span class="c-red b" slot="reference">点击此处加入社区</span>
							</el-popover>
							<span class="c-999">（点右上角...用浏览器打开，并长按可识别二维码）</span>
						</div>
					</div>
					<div v-show="!afficheVisible" @click="afficheVisible=true">......</div>
				</div>
			</div>

			<!--矿池类型选择tab-->
			<div class="pool-tab">
				<div class="pool-tab-wrap" >
						<span :class="{'active':key==poolTypeSelected}" v-for="(value, key, index) in poolTypes[lp]" @click="PoolTypeActive(key)">{{value}}
						</span>
				</div>
			</div>

			<!-- ///////////////////////////////////////////////項目塊//////////////////////////////////// -->
			<div class="data-block2" >
				<div class="item" :class="{'item-hot':item.rate>0}" v-for="item in dataPool">

					<!--到計時-->
					<div class="dateTime bg999 " v-show="timestampNow>item.end">
						<span v-if="lp==0">已結束</span>
						<br />&nbsp;
					</div>
					<div class="dateTime bgblue" v-show="timestampNow<item.end && timestampNow>item.start">
						<span v-if="lp==0">距結束</span>
						<br />{{(item.end-timestampNow)|ttp(lp)}}
					</div>
					<div class="dateTime " v-show="timestampNow<item.start">
						<span v-if="lp==0">距開始</span>
						<br />{{(item.start-timestampNow)|ttp(lp)}}
					</div>

					<!--倍數 如果0，則不顯示-->
					<div class="earn-rate" v-if="item.rate>0">{{item.rate}}X</div>

					<!--主要信息-->
					<div class="pool-header mt20 ofh">
						<div class="flex flex-jc-c">
							<img :src="'images/icon_'+item.lp+'.png'" class="icon">
							<img :src="'images/icon_'+item.target+'.png'" v-if="item.target" class="icon icon2">
						</div>
						<div class="header-right mt20">
							<div class="title">{{item.symbol}} {{item.series}}</div>
							<div class="tip">{{lang.pool_sc[lp]}} {{item.symbol}} {{lang.pool_earn[lp]}} XG</div>
						</div>
					</div>

					<!--操作-->
					<div class="bottomFix">
						<div class="mt10" v-if="item.type==0">
							<a class="type-link" :href="'https://justswap.org/?lang=zh-CN?tokenAddress='+item.tokenAddress+'&amp;type=add'"
							   target="_self">{{lang.pool_toGet[lp] + ' ' + item.symbol}} </a>
							<a href="#/main/lp"><i class="f18 el-icon-question"></i></a>
						</div>
						<div class="mt10" v-if="item.type!==0">
							<a class="type-link" :href="'https://justswap.org/?lang=zh-CN?tokenAddress='+item.tokenAddress+'&amp;type=swap'"
							   target="_self">{{lang.pool_toSwap[lp] +' ' + item.symbol}}</a>
						</div>

						<!-- <button class="main-bt w-50 m-auto mt10" @click="chooseShow(item)"
						        :disabled="chooseDisabled(item)">{{lang.pool_choose[lp]}}</button> -->
						<button class="main-bt w-50 m-auto mt20" @click="chooseShow(item)" v-if="timestampNow<item.end||(timestampNow>item.end&&dataPoolData[item.series][item.lp].staked==0)"
						        :disabled="chooseDisabled(item)">{{lang.pool_choose[lp]}}</button>
						<button class="main-bt w-50 m-auto mt20" @click="exitMine(item)" v-if="timestampNow>item.end&&dataPoolData[item.series][item.lp].staked!=0"
						        :disabled="chooseDisabled(item)">{{lang.pool_gotoExit[lp]}}</button>
						<!-- <button class="main-bt w-50 m-auto mt10" @click="exitMine(item)" v-if="timestampNow>item.end&&dataPoolData[item.series][item.lp].claimed>0"
						        :disabled="chooseDisabled(item)">{{lang.pool_gotoExit[lp]}}</button> -->
					</div>

					<!--簡略數據-->
					<div class="easy-data mt20" >
						<div class="cell">
							<div class="title">{{lang.pool_total[lp]}}</div>
							<div class="data">${{dataPoolData[item.series][item.lp].totalTrx*trxPrice|count}}</div>
						</div>

						<div class="cell">
							<div class="title">APY
								<el-tooltip class="" effect="dark" :content="lang.pool_apyTip[lp]" placement="left-start">
									<i class="f18 el-icon-question"></i>
								</el-tooltip>
							</div>
							<div class="data">{{dataPoolData[item.series][item.lp].apy}}%</div>
						</div>
					</div>

				</div>
			</div>



			<!-----------------------------------操作內容窗口-------------------------->
			<el-dialog :title="operaPool.symbol" width="430px" top="calc(50vh - 250px)" :visible.sync="dialogVisible"
			           :before-close="handleClose">

				<div class="tab-Content" >
					<!--				<div class="right c-red b" >退出請點右上角關閉↑</div>-->
					<!--標籤頁-->
					<div class="tabs">
						<b class="active" @click="activeOpWindowTab(0)">{{lang.pool_claim[lp]}}</b>
						<b @click="activeOpWindowTab(1)">{{lang.pool_lock[lp]}}</b>
						<b @click="activeOpWindowTab(2)">{{lang.pool_unlock[lp]}}</b>
						<b @click="activeOpWindowTab(3)">{{lang.hour_income_24[lp]}}</b>
					</div>
					<!--內容開始-->
					<div class="content">
						<div class="page lock_and_collect active">
							<div class="collect-wrap center" >
								<div class="title">{{operaPoolData.collect}}</div>
								<div class="tip">{{lang.pool_PendingClaim[lp]}}XG</div>
								<div class="mt30 flex flex-jc-c flex-ai-c">
									<button class="main-bt" @click="collectAll(operaPool)" v-if="operaPoolData.collect>0" :disabled="collectDisabled">{{lang.pool_oneKeyClaim[lp]}}</button>
									<button class="main-bt" @click="activeOpWindowTab(1)" v-if="operaPoolData.collect==0">{{lang.pool_gotoStakewk[lp]}}</button>
								</div>
							</div>
						</div>
						<!--鎖定-->
						<div class="page lock_and_collect">
							<div class="tip ">
								<span class="stakePopTitle">{{lang.pool_MyStake[lp]}}：{{operaPoolData.locked}} {{operaPool.symbol}}</span>
								<button class="stakeAll" @click="lockAmountMax()" :disabled="lockMaxDisabled">MAX</button>
							</div>
							<span class="stakeInput" :class="{disabled:operaPoolData.maxLock==0}">
									<input class="ant-input" type="number" v-model.trim="operaPoolData.sendLock" placeholder="0">
									<span class="ant-input-suffix">{{operaPool.symbol}}</span>
								</span>
							<div class="tip mt10 bottomFix">
									<span class="stakePopTitle">
										{{lang.pool_MaxStake[lp]}}：{{operaPoolData.maxLock}} {{operaPool.symbol}}
										<a href="#/main/lp" v-if="operaPool.type==0"><i class="f18 el-icon-question"></i></a>
									</span>
								<a class="type-link" style="color:#f60" v-if="operaPool.type==0" :href="'https://justswap.org/?lang=zh-CN?tokenAddress='+operaPool.tokenAddress+'&amp;type=add'"
								   target="_self">{{lang.pool_toGet[lp]}}</a>
								<a class="type-link" style="color:#f60" v-if="operaPool.type!==0" :href="'https://justswap.org/?lang=zh-CN?tokenAddress='+operaPool.tokenAddress+'&amp;type=swap'"
								   target="_self">{{lang.pool_toSwap[lp]}}</a>
							</div>

							<!--這裡有2個按鈕，根據authorize來判斷渲染-->
							<div class="mt20">
								<button class="main-bt w-100" @click="authorize(operaPool)" v-if="operaPoolData.authorize==0" :disabled="endDisabled">{{lang.pool_Approve[lp]}}
									{{operaPool.symbol}}</button>
								<button class="main-bt w-100" @click="runLock(operaPool)" v-if="operaPoolData.authorize==1" :disabled="lockDisabled">{{lang.pool_lockMining[lp]}}</button>
								<!-- <button class="main-bt w-100" @click="runLock(operaPool)" v-if="operaPoolData.authorize==1" >去獲取LP TOKEN</button> -->
							</div>
						</div>

						<!--收穫-->
						<div class="page lock_and_collect">
							<div class="tip">
								<span class="stakePopTitle">{{lang.pool_MyStake[lp]}}：{{operaPoolData.locked}} {{operaPool.symbol}}</span>
								<button class="stakeAll" @click="unlockAmountMax()" :disabled="unLockMaxDisabled">MAX</button>
							</div>
							<span class="stakeInput" :class="{disabled:operaPoolData.maxUnLock==0}">
									<input class="ant-input" type="number" v-model.trim="operaPoolData.sendUnlock" placeholder="0">
									<span class="ant-input-suffix">{{operaPool.symbol}}</span>
								</span>
							<div class="max-opera-num">
								{{lang.pool_MaxUnStake[lp]}}：<span>{{operaPoolData.maxUnLock}}</span> {{operaPool.symbol}}
							</div>
							<div class="mt10">
								<button class="main-bt w-100 " @click="runUnLock(operaPool)" :disabled="unLockDisabled">{{lang.pool_claim_unlock[lp]}}</button>
							</div>
						</div>

						<div class="page lock_and_collect">
							<div class="collect-wrap center">
								<div class="tip">
									{{lang.locktest1[lp]}}≈ {{ incomeDetail(operaPool,1,2) }} USD
								</div>
								<div class="tip">
									{{lang.locktest2[lp]}}≈ {{ incomeDetail(operaPool,1,1) }} USD
								</div>
								<div class="tip">
									{{lang.locktest3[lp]}}≈ {{ incomeDetail(operaPool,24,1) }} USD
								</div>
							</div>
						</div>

					</div>
					<!--內容結速-->
				</div>
				<!--tab結束-->
			</el-dialog>
		</div>
		<!--main 结束 -->
		<footter showLink></footter>
	</div>
</template>


<script type="text/javascript">

	/*加载资源*/
	import lang2 from './farm_lang.js' //页面独立语言配置，没有则删除
	import { mixins } from '@/mixins/mixins' //公共混入
	import { mixinsUtils } from '@/mixins/mixins.utils' //公共混入
	import { mapState } from 'vuex' //vuex工具
	import { _DATA_POOL_,_DATA_POOLDATA_ } from '@/libs/pool' // 导入重要配置

	import { getEffectiveValue, getLocalStorage, msgInterface, setLocalStorage } from '@/libs/site.utils'
	import {
		approve,
		balanceOf, caculateApy,
		CALLBACK_ERR,
		dev,
		earned,
		exit, getAllocatable,
		getBalanceAndApprove2,
		getInfoAll2,
		getReward,
		hex2Num, INITDATA_TIME_LIMIT,
		stake,
		stakeTrx,
		withdrawAndGetReward,
	} from '@/libs/tron.lib'

	/*组件*/
	import top from '@/components/top.vue'
	import footter from "@/components/footer.vue"
	import banner from '@/components/banner.vue'
	import pageTip from '@/components/pageTip.vue'
	import floatTip from '@/components/floatTip.vue'
	import tipManage from "@/components/tipManage";
	import {getJustWapTokenAndIssuanceTokenRate} from "../../../axios/api";
	let vueObject;
	export default {
		name:"farm",
		components: { top,footter,banner,pageTip,floatTip,tipManage },
		mixins:[mixins,mixinsUtils],
		props:[],
		data () {
			return {
				//页面独立的语言配置
				lang:Object.freeze(lang2),

				/*矿池tab用的*/
				poolTypes: [
					{ '0': '未開始', '1': '進行中', '2': '已結束', },
					{ '0': 'Comming', '1': 'Active', '2': 'Ended', }
				],
				poolTypeSelected: '1',


				//控制值
				dialogVisible: false, //操作窗口是否顯示
				afficheVisible:true,//公告可见性
				menuFlag: false, //手機端的全屏菜單顯示控制
				timestampNow: 0, //此時的時間戳，由定時器不斷賦值
				timestampInit: 0, //頁面初始化時的時間戳，用於判斷項目是否結束
				timeHandler: null, //倒時的定時器
				flag_game: 1, //游戏中心的上线提示显示标记
				timerTRXPoolStatus: null, //trx和矿池状态的定时器
				timerOperaPoolData: null, //操作数据的刷新定时器

				//矿池
				initPool: _DATA_POOL_,
				//以lp來對號入座的數據,這個也從接口讀取
				dataPoolData: _DATA_POOLDATA_,
				//代币和justwap lp代币转换比率
				tokenAndLpTokenRatio: "",

				//操作窗口正在操作的對象，點擊時再賦值過來
				operaPool: {
					pool: "",
					token: "",
					tokenAddress: "",
					symbol: "TOKEN LP",
					lp: "TOKEN",
					xgSupply: 0,
					start: 0,
					end: 0,
					decimal: 0,
					tokenDecimal: 0,
					rate: "0",

				},
				//操作對象的請示數據，從後台請求數據
				//同時也將操作輸入的值綁定在這個對象內
				operaPoolData: {
					authorize: 0, //是否授權，打開操作窗口的時候，就要重新處理這個數據
					locked: 0, //已鎖定（請求）
					collect: 0, //待收穫（請求）
					maxLock: 0, //最多可鎖定（請求）
					maxUnLock: 0, //最多可解鎖收穫（請求）
					sendLock: 0, //操作窗口輸入的鎖定值
					sendUnlock: 0, //操作窗口輸入的解鎖值

				},

				//trx数据
				totalTrx: 0,
				totalRelease: 0
			};
		},
		beforeCreate: function () {
			vueObject = this;
		},
		computed:{

			//關於 vue對disable的控制 https://www.cnblogs.com/wrestle-mania/p/6939571.html


			//dataPool改为计算对象，主要是用于后来改为按type来显示
			//注意：filter方法不会操作原始数据
			dataPool () {
				return _DATA_POOL_.filter(item => item.status == this.poolTypeSelected)
			},

			//計算單獨的收穫按鈕是否讓它失效。
			collectDisabled () {
				if (this.operaPoolData.collect == 0) { //如果可收穫數等於0，就讓按鈕失敗
					return true
				}
				return false;
			},

			//计算是否能最大解锁
			unLockMaxDisabled () {
				if (this.operaPoolData.maxUnLock == 0) {
					return true;
				}
				return false;
			},

			//計算解鎖收穫按鈕是否讓它失效，返回true，也就是激活disabled屬性
			unLockDisabled () {
				if (this.operaPoolData.maxUnLock == 0 || this.operaPoolData.sendUnlock <= 0) {
					return true;
				} else if (this.operaPoolData.sendUnlock > this.operaPoolData.maxUnLock) {
					return true;
				}
				return false
			},

			//计算是否能最大锁定
			lockMaxDisabled () {
				if (this.operaPool.end < this.timestampNow) {
					return true;
				}
				if (this.operaPoolData.authorize == 0) {
					return true;
				}
				return false;
			},

			//計算鎖定按鈕是否讓它失效，返回true，也就是激活disabled屬性
			lockDisabled () {
				if (this.operaPool.end < this.timestampNow) {
					return true;
				}

				if (this.operaPoolData.authorize == 0) {
					return true;
				} else if (this.operaPoolData.maxLock == 0 || this.operaPoolData.sendLock <= 0) {
					return true;
				} else if (this.operaPoolData.sendLock > this.operaPoolData.maxLock) {
					return true;
				}
				return false
			},

			//計算首頁項目列表中的選擇按鈕是否讓它失效
			// 注意：因为要作为方法使用，所以这里要返回了一个匿名函数
			chooseDisabled () {
				return function (item) {
					//这他妈什么条件？
					//当前矿池用户还有质押时
					if (this.dataPoolData[item.series][item.lp].staked > 0) { return false; }
					//如果未開始
					if (this.timestampNow < item.start) { return true }
					//如果已結束
					if (this.timestampNow > item.end) { return true }
					//如果已經過期或未開始
					return false
				}
			},

			//矿池结束后（到截止时间），也要失效
			endDisabled () {
				return this.operaPool.end <= this.timestampNow;
			},

            //矿池预估收益计算方法
            incomeDetail(){
                return (item, hr, type) => {
                    if (item.lp == 'TOKEN') {
                        return "";
                    }
                    let that = vueObject;

                    //矿池年化率
                    let poolApy = that.dataPoolData[item.series][item.lp].calApy;
                    //锁仓数量
                    let lockedPosition = that.dataPoolData[item.series][item.lp].staked;

                    //用户锁仓usdt。usdt不转换，trx转换usdt xg也是转换usdt
                    let userHedging;
                    if (item.lp.indexOf("USDT") != -1) userHedging = lockedPosition;
                    if (item.lp.indexOf("TRX") != -1) userHedging = lockedPosition * that.trxPrice;
                    if (item.lp.indexOf("XG") != -1) {
                        //计算xg数量
                        let gbtNum = lockedPosition * that.tokenAndLpTokenRatio;
                        //xg数量转换usdt价值
                        let gbtVal = gbtNum * that.xg.toUsdtPrice;
                        //一个xg价值$0.393。一个trx价值$0.056。那么1个gbt价值0.394/0.056=7trx
                        let trxPrice = that.xg.toUsdtPrice / that.trxPrice;
                        //按xg*trx价值，算出对应的trx价值。详细清单lp和justwap浏览器关系
                        let trxVal = trxPrice * gbtNum;
                        trxVal = trxVal * that.trxPrice;
                        userHedging = gbtVal + trxVal;
                    }
                    userHedging = userHedging.toFixed(3);
                    //console.log(lockedPosition, poolApy / 100, userHedging, that.tokenAndLpTokenRatio)

                    //锁仓x小时收益。1年=8760(小时)
                    let hourlyEarnings = ((userHedging * (poolApy / 100) / 8760) * hr).toFixed(5);

                    //如果是Nan则返回加载中
                    let loading = that.lp == 0
                        ? '计算中...'
                        : 'Loading...'
                    hourlyEarnings = isNaN(hourlyEarnings) == true
                        ? loading
                        : hourlyEarnings

                    //返回收益或锁仓资金U
                    return type == 1
                        ? hourlyEarnings
                        : userHedging;
                }
            }
		},

		created () {

			//时间相关处理
			this.timestampNow = parseInt((new Date().getTime()) / 1000) //馬上初始化用於倒計時的此刻時間
			this.timestampInit = parseInt((new Date().getTime()) / 1000) //初始化頁面打開時的時間
			//下面这个定时器本来是1秒，设间隔长点，节省点页面cpu占用
			this.timeHandler = setInterval(() => {
				this.timestampNow = parseInt((new Date().getTime()) / 1000)
			}, 10000)

			//處理tip3的顯示
			localStorage.getItem('flag_game') == '0' && (this.flag_game = 0)

			//读取部分字段的缓存数据
			this.initPool.forEach((item) => {
				this.dataPoolData[item.series][item.lp].totalTrx = getLocalStorage(item.series + ":" + item.lp + ":totalTrx",0);
				this.dataPoolData[item.series][item.lp].apy  = getLocalStorage(item.series + ":" + item.lp + ":apy","NAN");
			})
		},

		mounted () {
			//加载lp和代币比率
			this.getJustWapTokenAndIssuanceTokenRate();

			let that = this

			//创建监听事件
			this.$root.eventHub.$on('loadInitData',() => {
				// debug && this.$notify({ title: '定时器', message: '重新刷新数据中....',duration:2000  })
				this.initData();
			})

			//延迟初始化数据，否则tronWeb未初始化，方法会报错
			window.setTimeout(() => {
				that.initData()
			},INITDATA_TIME_LIMIT)

			//定时读取trx和重置矿池状态 (已增加销毁)
			this.timerTRXPoolStatus = setInterval(() => {
				// console.log('启定动时器：定时读取trx和重置矿池状态')
				this.calTotalTrx();
				this.autoChangeStatus();
			}, 5000);

			//定进刷新操作对象数据 (已增加销毁)
			this.timerOperaPoolData = setInterval(() => {
				// console.log('启定动时器：定进刷新操作对象数据')
				this.loadSenderFarmInfo();
			}, 10000);
		},


		methods:{

			//初始化数据, 如果tronweb未初始化会报错，这里使用try-catch来好看点
			initData () {
				let that = this
				console.log('读取本页的默认数据')
				try {
					if (tronWeb) {
						this.loadPoolInfo()
					}
				} catch (e) {
					console.error('tronweb可能还没初始化...' + e)
					window.setTimeout(() => {
						that.initData()
					}, INITDATA_TIME_LIMIT)
				}

			},

			//获取：代币和justwap lp代币转换比率
			getJustWapTokenAndIssuanceTokenRate() {
				let param = {
					poolAddress: this.xg.pairAddress,
					tokenAddress: this.xg.address,
					justWapTokenAndIssuanceTokenRate: 0,
					act: "justWapTokensAndIssuingTokenRatesOutputInterface"

				}

				let that = this;
				getJustWapTokenAndIssuanceTokenRate(param).then(result => {
					that.tokenAndLpTokenRatio = result.data.tokenAndLpTokenRatio
				})
			},

			//加载矿池数据
			loadPoolInfo () {
				let that = this
				that.initPool.forEach((item, index) => {
					//已启动且锁定资产未解锁完、并且是当前选择的类型
					if (item.status > 0 && !item.isClean && (item.status == that.poolTypeSelected)) {
						getInfoAll2(item.pool, that.sender, (rsp) => {
							if (rsp != CALLBACK_ERR) {
								let totalLock = getEffectiveValue(rsp, 7, 64); //总锁仓数量
								let staked = getEffectiveValue(rsp, 9, 64); //当前用户锁仓数量
								let claimed = getEffectiveValue(rsp, 11, 64); //当前用户可收获数量
								let trxAmount = getEffectiveValue(rsp, 13, 64); //矿池trx数量
								let tokenAmount = getEffectiveValue(rsp, 15, 64); //矿池代币数量

								that.dataPoolData[item.series][item.lp].total = hex2Num(totalLock, 6);
								that.dataPoolData[item.series][item.lp].trxAmount = hex2Num(trxAmount, 6);
								that.dataPoolData[item.series][item.lp].lpAmount = hex2Num(tokenAmount, item.tokenDecimal);
								that.dataPoolData[item.series][item.lp].staked = hex2Num(staked, item.decimal);
								that.dataPoolData[item.series][item.lp].claimed = hex2Num(claimed, that.xg.decimal);
								that.dataPoolData[item.series][item.lp].allocatable = getAllocatable(item.start, item.end, item.xgSupply);

								if (item.type > 0) { //非lp的token池
									that.dataPoolData[item.series][item.lp].lpAmount = that.dataPoolData[item.series][item.lp].total;
								}

								let totalTrx = 0;
								switch (item.type) {
									case 0:
									default:
										totalTrx = that.dataPoolData[item.series][item.lp].trxAmount * 2;
										break;
									case 1: //token池
									case 2: //trx池
										totalTrx = that.dataPoolData[item.series][item.lp].trxAmount;
										break;
								}
								that.dataPoolData[item.series][item.lp].totalTrx = totalTrx;

								if (item.status == 1) { //正在进行中的计算apy等数据
									that.dataPoolData[item.series][item.lp].calApy = caculateApy(item.xgSupply, item.start, item.end, that.xg.toUsdtPrice,
										totalTrx * that.trxPrice);
									that.dataPoolData[item.series][item.lp].apy = that.dataPoolData[item.series][item.lp].calApy;
								}
								//储存部分字段的到本地储存中
								setLocalStorage(item.series + ":" + item.lp + ":totalTrx",totalTrx);
								setLocalStorage(item.series + ":" + item.lp + ":apy",that.dataPoolData[item.series][item.lp].calApy);
							}
						});
					}

				})
				that.calTotalTrx(); //同时刷新trx数据
			},




			//選擇操作項目（处理）
			chooseShow (item) {
				let that = this
				if (!this.tornlinkToken) {
					this.openWallet();
				} else {
					this.operaPool = Object.assign({}, this.operaPool, item);
					this.activeOpWindowTab(0); //默認激活第一個tab標籤，也就是收穫按鈕那頁面
					this.opWindowCloseCallBack(); //進行相關處理

					//進行相關判斷
					if (that.operaPool.type == 2) { //trx礦池
						that.operaPoolData.authorize = 1;
						tronWeb.trx.getBalance(that.sender).then(amount => {
							that.operaPoolData.maxLock = hex2Num(tronWeb.toHex(amount), that.operaPool.decimal);
							// if(that.operaPoolData.sendLock===0){
							// 	that.operaPoolData.sendLock = '';
							// }
						})
					} else {
						//獲取可鎖定數量以及是否授權
						getBalanceAndApprove2(that.operaPool.token, that.operaPool.pool, that.sender, (rsp) => {
							if (rsp.length === 256) {
								let amount = rsp.substring(128, 192);
								let approve = rsp.substring(192);
								//可鎖倉數量
								that.operaPoolData.maxLock = hex2Num(amount, that.operaPool.decimal);
								that.operaPoolData.authorize = tronWeb.toBigNumber("0x" + approve) > 0 ? 1 : 0; //是否已經授權
								if (that.operaPoolData.sendLock === 0) {
									that.operaPoolData.sendLock = '';
								}
							}

						});


					}
					//獲取已鎖定數量
					balanceOf(that.operaPool.pool, that.sender, (rsp) => {
						that.operaPoolData.locked = hex2Num(rsp, that.operaPool.decimal);
						that.operaPoolData.maxUnLock = that.operaPoolData.locked;
						if (that.operaPoolData.sendUnlock === 0) {
							that.operaPoolData.sendUnlock = '';
						}
					});
					//獲取可收穫數量
					earned(that.operaPool.pool, that.sender, (rsp) => {
						that.operaPoolData.collect = hex2Num(rsp, that.xg.decimal);
					});

					that.dialogVisible = true;
				}
			},


			//重载操作数据的数据（处理）
			loadSenderFarmInfo () {
				let that = this;
				if (that.dialogVisible) {
					if (that.operaPool.type == 2) { //trx礦池
						that.operaPoolData.authorize = 1; //trx默认授权的
						//获取用户trx资产
						tronWeb.trx.getBalance(that.sender).then(amount => {
							that.operaPoolData.maxLock = hex2Num(tronWeb.toHex(amount), that.operaPool.decimal)-20;
							that.operaPoolData.maxLock = that.operaPoolData.maxLock>0?that.operaPoolData.maxLock:0;
							if (that.operaPoolData.sendLock === 0) {
								that.operaPoolData.sendLock = '';
							}
						})
					} else {
						//获取锁定币种数量 以及 对矿池的授权量
						getBalanceAndApprove2(that.operaPool.token, that.operaPool.pool, that.sender, (rsp) => {
							if (rsp.length === 256) {
								let amount = rsp.substring(128, 192);
								let approve = rsp.substring(192);
								//可鎖倉數量
								that.operaPoolData.maxLock = hex2Num(amount, that.operaPool.decimal);
								if (that.operaPoolData.sendLock === 0) {
									that.operaPoolData.sendLock = '';
								}
								that.operaPoolData.authorize = tronWeb.toBigNumber("0x" + approve) > 0 ? 1 : 0; //是否已經授權
							}
						});
					}

					//获取用户当前已经锁仓的数量
					balanceOf(that.operaPool.pool, that.sender, (rsp) => {
						that.operaPoolData.locked = hex2Num(rsp, that.operaPool.decimal);
						that.operaPoolData.maxUnLock = that.operaPoolData.locked;
						if (that.operaPoolData.sendUnlock === 0) {
							that.operaPoolData.sendUnlock = '';
						}
					});

					//获取用户当前可收获的数量
					earned(that.operaPool.pool, that.sender, (rsp) => {
						that.operaPoolData.collect = hex2Num(rsp, that.xg.decimal);
					});
				}
			},



			//授權（处理）
			authorize (item) {
				let that = this;
				msgInterface(that.LangSet(['授權', 'Approve']), '', 1, '', item.symbol);
				approve(item.pool, item.token, that.sender, (status, txid) => {
					if (status === 0) { //失敗
						msgInterface(that.LangSet(['授權', 'Approve']), '', -1, '', item.symbol);
					} else if (status === 1) { //成功
						msgInterface(that.LangSet(['授權', 'Approve']), '', 2, 'https://tronscan.io/#/transaction/' + txid, item
							.symbol);
					} else if (status === -1) { //取消
						msgInterface(that.LangSet(['授權', 'Approve']), '', 3, '', item.symbol);

					}
				}, (txid, status) => {
					if (status === "SUCCESS") {
						that.$message({
							type: "success",
							message: that.LangSet(['授權', 'Approve']) + item.symbol + that.LangSet(['成功', 'SUCCESS'])
						});
					} else if (status === "OUT_OF_ENERGY") {
						msgInterface(that.LangSet(['錢包中請至少保留', 'Minimum wallet balance']), 20, 0, '', "TRX");
					} else {
						that.$message({
							type: "error",
							message: that.LangSet(['授權', 'Approve']) + item.symbol + that.LangSet(['失敗', 'FAIL'])
						});
					}

				});
			},



			//鎖倉操作（处理）
			runLock (item) {
				let that = this;
				let sendLock = this.operaPoolData.sendLock;
				msgInterface(that.LangSet(['鎖倉', 'Stake']), sendLock, 1, '', item.symbol)

				if (item.type == 2) { //trx礦池
					stakeTrx(item.pool, that.sender, sendLock, item.decimal, (status, txid) => {
						if (status === 0) { //失敗
							msgInterface(that.LangSet(['鎖倉', 'Stake']), sendLock, -1, '', item.symbol);
						} else if (status === 1) { //成功
							msgInterface(that.LangSet(['鎖倉', 'Stake']), sendLock, 2, 'https://tronscan.io/#/transaction/' + txid,
								item.symbol);
							this.opWindowCloseCallBack();
						} else if (status === -1) { //取消
							msgInterface(that.LangSet(['鎖倉', 'Stake']), sendLock, 3, '', item.symbol);

						}
					}, (txid, status) => {
						if (status === "SUCCESS") {
							that.$message({
								type: "success",
								message: that.LangSet(['鎖倉', 'Stake']) + sendLock + item.symbol + that.LangSet(['成功', 'SUCCESS'])
							});
						} else if (status === "OUT_OF_ENERGY") {
							msgInterface(that.LangSet(['錢包中請至少保留', 'Minimum wallet balance']), 20, 0, '', "TRX");
						} else {
							that.$message({
								type: "error",
								message: that.LangSet(['鎖倉', 'Stake']) + sendLock + item.symbol + that.LangSet(['失敗', 'FAIL'])
							});
						}

					});

				} else { //非trx礦池

					stake(item.pool, that.sender, sendLock, item.decimal, (status, txid) => {
						if (status === 0) { //失敗
							msgInterface(that.LangSet(['鎖倉', 'Stake']), sendLock, -1, '', item.symbol);
						} else if (status === 1) { //成功
							msgInterface(that.LangSet(['鎖倉', 'Stake']), sendLock, 2, 'https://tronscan.io/#/transaction/' + txid,
								item.symbol);
							this.opWindowCloseCallBack();

						} else if (status === -1) { //取消
							msgInterface(that.LangSet(['鎖倉', 'Stake']), sendLock, 3, '', item.symbol);

						}
					}, (txid, status) => {

						if (status === "SUCCESS") {
							that.$message({
								type: "success",
								message: that.LangSet(['鎖倉', 'Stake']) + sendLock + item.symbol + that.LangSet(['成功', 'SUCCESS'])
							});
						} else if (status === "OUT_OF_ENERGY") {
							msgInterface(that.LangSet(['錢包中請至少保留', 'Minimum wallet balance']), 20, 0, '', "TRX");
						} else {
							that.$message({
								type: "error",
								message: that.LangSet(['鎖倉', 'Stake']) + sendLock + item.symbol + that.LangSet(['失敗', 'FAIL'])
							});
						}
					});
				}
			},





			//解鎖操作提交 （处理）
			runUnLock (item) {
				let that = this;
				let sendUnlock = this.operaPoolData.sendUnlock;
				msgInterface(that.LangSet(['解鎖', 'unLock']), sendUnlock, 1, '', item.symbol);

				withdrawAndGetReward(item.pool, that.sender, sendUnlock, item.decimal, (status, txid) => {
					if (status === 0) { //失敗
						msgInterface(that.LangSet(['解鎖', 'unLock']), sendUnlock, -1, '', item.symbol);
					} else if (status === 1) { //成功
						msgInterface(that.LangSet(['解鎖', 'unLock']), sendUnlock, 2, 'https://tronscan.io/#/transaction/' + txid, item.symbol);
						this.opWindowCloseCallBack(); //同时清空sendLock和sendUnlock
					} else if (status === -1) { //取消
						msgInterface(that.LangSet(['解鎖', 'unLock']), sendUnlock, 3, '', item.symbol);

					}
				}, (txid, status) => {
					if (status === "SUCCESS") {
						that.$message({
							type: "success",
							message: that.LangSet(['解鎖', 'unLock']) + sendUnlock + item.symbol + that.LangSet(['成功', 'SUCCESS'])
						});
					} else if (status === "OUT_OF_ENERGY") {
						msgInterface(that.LangSet(['錢包中請至少保留', 'Minimum wallet balance']), 20, 0, '', "TRX");
					} else {
						that.$message({
							type: "error",
							message: that.LangSet(['解鎖', 'unLock']) + sendUnlock + item.symbol + that.LangSet(['失敗', 'FAIL'])
						});
					}

				});
			},



			//鎖定全部數量（賦值）
			lockAmountMax () {
				this.operaPoolData.sendLock = this.operaPoolData.maxLock
			},

			//收穫全部數量（賦值）
			unlockAmountMax () {
				this.operaPoolData.sendUnlock = this.operaPoolData.maxUnLock
			},

			//收穫（处理）
			collectAll (item) {
				let that = this;
				var collect = this.operaPoolData.collect; //待收穫數量
				msgInterface(that.LangSet(['收穫', 'Claim']), collect, 1, '', "XG");

				getReward(item.pool, that.sender, collect, item.decimal, (status, txid) => {
					if (status === 0) { //失敗
						msgInterface(that.LangSet(['收穫', 'Claim']), collect, -1, '', "XG");
					} else if (status === 1) { //成功
						msgInterface(that.LangSet(['收穫', 'Claim']), collect, 2, 'https://tronscan.io/#/transaction/' + txid, "XG");
					} else if (status === -1) { //取消
						msgInterface(that.LangSet(['收穫', 'Claim']), collect, 3, '', "XG");
					}
				}, (txid, status) => {
					if (status === "SUCCESS") {
						that.$message({
							type: "success",
							message: that.LangSet(['收穫', 'Claim']) + collect + "XG" + that.LangSet(['成功', 'SUCCESS'])
						});
					} else if (status === "OUT_OF_ENERGY") {
						msgInterface(that.LangSet(['錢包中請至少保留', 'Minimum wallet balance']), 20, 0, '', "TRX");
					} else {
						that.$message({
							type: "error",
							message: that.LangSet(['收穫', 'Claim']) + collect + "XG" + that.LangSet(['失敗', 'FAIL'])
						});
					}

				});
			},

			//退出矿池（处理）
			exitMine (item) {
				let that = this;
				msgInterface(that.LangSet(['退出', 'Exit']), '', 1, '', item.pool.lp);
				exit(item.pool, that.sender, (status, txid) => {
					if (status === 0) { //失敗
						msgInterface(that.LangSet(['退出', 'Exit']), '', -1, '', item.pool.lp);
					} else if (status === 1) { //成功
						msgInterface(that.LangSet(['退出', 'Exit']), '', 2, 'https://tronscan.io/#/transaction/' + txid, item.pool.lp);
					} else if (status === -1) { //取消
						msgInterface(that.LangSet(['退出', 'Exit']), '', 3, '', item.pool.lp);
					}
				}, (txid, status) => {
					if (status === "SUCCESS") {
						that.$message({
							type: "success",
							message: that.LangSet(['退出', 'Exit']) + item.pool.lp + that.LangSet(['成功', 'SUCCESS'])
						});
					} else if (status === "OUT_OF_ENERGY") {
						msgInterface(that.LangSet(['錢包中請至少保留', 'Minimum wallet balance']), 20, 0, '', "TRX");
					} else {
						that.$message({
							type: "error",
							message: that.LangSet(['退出', 'Exit']) + item.pool.lp + that.LangSet(['失敗', 'FAIL'])
						});
					}

				})
			},

			//全部TRX量，全部释放量
			calTotalTrx () {
				let that = this;
				let sum = 0;
				let relase = 0;
				that.initPool.forEach((item) => {
					sum += (+that.dataPoolData[item.series][item.lp].totalTrx);
					relase += (item.xgSupply - getAllocatable(item.start, item.end, item.xgSupply));
				})
				that.totalTrx = sum;
				that.totalRelease = relase;
			},

			//在设置时间前后的一段时间改变矿池状态
			autoChangeStatus () {
				let that = this;
				that.initPool.forEach((item) => {
					let _status = item.status;
					if (_status == 0) {
						if (item.start - that.timestampNow <= 900) { //距离开始一小时 自动激活为进行中
							_status = 1;
						}
					} else if (_status == 1) {
						if (that.timestampNow - that.timestampNow >= 900) { //已结束超过一小时  自动变更为已结束
							_status = 2;
						}
					}
					item.status = _status;
				})
			},


			//關閉操作窗口
			handleClose (done) {
				this.opWindowCloseCallBack(); //進行相關處理
				done() //dialog插件需要的回调
			},

			//關閉操作窗口時，要處理的東西
			opWindowCloseCallBack () {
				let that = this;
				//重置操作的數據對象operaPoolData
				that.operaPoolData.sendLock = '';
				that.operaPoolData.sendUnlock = '';
			},

			//激活操作窗口的tab，從0開始
			activeOpWindowTab (_index) {
				$(".tabs").children('b').removeClass('active')
				$(".tabs").children('b').eq(_index).addClass('active');
				$(".tab-Content .content .page").removeClass('active');
				$(".tab-Content .content .page").eq(_index).addClass('active')
			},
			//跳轉到LPtoken說明頁面
			ReadMelpToken () {
				this.$router.push('/main/lp')
			},

			//隱藏游戏中心提醒
			hideTipgame () {
				localStorage.setItem('flag_game', '0')
				this.flag_game = 0
			},

			//选择矿池tab显示类型
			PoolTypeActive (key) {
				if (this.poolTypeSelected != key) {
					this.poolTypeSelected = key
					this.initData(); //要重新加载矿池相关数据，因为是依赖poolTypeSelected进行筛选的
				}
			}
		},


		beforeDestroy () {
			this.$root.eventHub.$off('loadInitData')
			clearInterval(this.timeHandler) //清除矿池倒计时定时器
			clearInterval(this.timerTRXPoolStatus) //清除trx和矿池状态的定时器
			clearInterval(this.timerOperaPoolData) //清除操作数据的刷新定时器
		},
	};
</script>


<style lang="less" scoped>

	/*公共变量*/
	@import '~@/assets/global.less';

	/*页面css*/
	@import './farm.less';

	/*页面独有标题样式*/
	//.page-tips{color: #e00;font-weight: bold;;background-color: #ffe800;}


	/***********************************************适应**********************************************/
	/***********************************************适应**********************************************/
	/***********************************************适应**********************************************/
	@media screen and (max-width: @MINSCREEN){

	}
</style>
